<?php


namespace Yond\LaravelDomain\Models\Concerns;


use Illuminate\Database\Eloquent\Model;

/**
 * Trait HasBelongsToManyField
 * @mixin Model
 */
trait HasBelongsToManyField
{
    public array $queuedAttachFields = [];

    public static function bootHasBelongsToManyField()
    {
        static::created(function (Model $model) {
            /** @var self $model */
            foreach ($model->queuedAttachFields as $relation => $value) {
                if (is_array($value)) {
                    $model->{$relation}()->attach($value);
                }
            }
            $model->queuedAttachFields = [];
        });
    }
}
